--[[
Name: BrownieHelper
Developed by: Sonora (The Dragon Flight)
Website: http://sonora.kirintor.googlepages.com/contents
SVN: http://code.google.com/p/browniehelper/source/browse
License: GNU General Public License v3
]]

function ViewDatabaseSourcesFrame:Initialize(app)
    --app is the brownie helper app
    
    --Save the brownie helper app
    self.app = app
    
    --Setup our table's fields
    ViewDatabaseSourcesTable:setWidths({87,185,185,57})
    ViewDatabaseSourcesTable:setFields({"Character","Last external update", "Last in-game update","Version"})
    ViewDatabaseSourcesTable.candeselect = false
    ViewDatabaseSourcesTable:registerSelectionCallback(function() ViewDatabaseSourcesDownloadButton:Enable() end)
    
    --Make sure we call OnShow
    self:updateView()
    self:queryBrownieHelper()
    
end

function ViewDatabaseSourcesFrame:queryBrownieHelper()

    --If we're in a raid, query everyone in the raid
    if GetNumRaidMembers() >0 then
        for idx = 1,GetNumRaidMembers() do
            local unitid = "raid"..tostring(idx)
            self.app:callHasBrownieHelper(UnitName(unitid))
        end
        
    --If we're in a party, query everyone in the party
    elseif GetNumPartyMembers() >0 then
        for idx = 1,GetNumPartyMembers() do
            local unitid = "party"..tostring(idx)
            self.app:callHasBrownieHelper(UnitName(unitid))
        end
    end
    
    --query everyone in the guild, comming soon...
    
end

function ViewDatabaseSourcesFrame:updateView()

    --Update the view based on who we have around to get points from
    ViewDatabaseSourcesTable:clearRows()
    
    if self.app.brownieHelperRoster then
        for characterName, rosterInfo in pairs(self.app.brownieHelperRoster) do
            if rosterInfo.brownieHelperVersion then
                ViewDatabaseSourcesTable:addRow({
                    ["Character"] = characterName,
                    ["Last external update"] = (rosterInfo.lastExternalUpdate or "never"),
                    ["Last in-game update"] = (rosterInfo.lastInternalUpdate or "never"),
                    ["Version"] = rosterInfo.brownieHelperVersion,
                })
            end
        end
    end
    
    --Update the last updated label for us
    ViewDatabaseSourcesFrameLastUpdatedLabel:SetText(self.app:getDb().lastExternalUpdate)
    
    --Hide the download button
    if #ViewDatabaseSourcesTable:getSelections()<1 then ViewDatabaseSourcesDownloadButton:Disable() end
    
end

function ViewDatabaseSourcesFrame:OnDownload()
    local row = ViewDatabaseSourcesTable:getSelections()[1]
    
    yesnoDialog(
        "Are you sure you want to update the local database with points from "..row.Character.."?",
        function(response)
            if response==true then
                ViewDatabaseSourcesFrameLastUpdatedLabel:SetText("update in progress")
                self.app:callGetPointsDatabase(row.Character)
            end
        end
    )
    
end

function ViewDatabaseSourcesFrame:OnRefresh() self:queryBrownieHelper() end
function ViewDatabaseSourcesFrame:OnClose() self:Hide() end

--[[
Communications protocol to get points from another player

]]
BrownieHelper:registerCommand("GetPointsDatabase")
function BrownieHelper:requestGetPointsDatabase(sender, args, responseCall)
    --Respond with our whole points database (even if we're in client mode)
    responseCall({pointsDb=self:getDb().pointsDb, runDb=self:getDb().runDb, playerDb=self:getDb().playerDb, lastExternalUpdate=self:getDb().lastExternalUpdate})
end

function BrownieHelper:respondGetPointsDatabase(sender, args)
    local localPointsDb = self:getDb().pointsDb
    local localRunDb = self:getDb().runDb
    local localPlayerDb = self:getDb().playerDb
    
    --Don't overwrite whole point hashes they might be missing
    for poolName, poolDb in pairs(args.pointsDb) do
        --If we don't have a pool by this name make on
        if localPointsDb[poolName]==nil then localPointsDb[poolName]={} end
        
        --Don't overwrite player entries they may be missing
        for playerName, playerPoints in pairs(poolDb) do
            localPointsDb[poolName][playerName] = playerPoints
        end
    end
    
    --Don't overwrite whole run hashes they might be missing
    for name, runEntry in pairs(args.runDb) do
        localRunDb[name] = runEntry
    end
    
    --Don't over write the whole player db
    for name, playerInfo in pairs(args.playerDb) do
        if localPlayerDb[name] == nil then
            localPlayerDb[name] = {class="",aliases={}}
        end
        for i, alias in playerInfo.aliases do
            if not has(localPlayerDb[name].aliases, alias) then table.insert(localPlayerDb[name].aliases, alias) end
        end
    end
    
    --Save the last external sync as our own
    self:getDb()['lastExternalUpdate'] = args.lastExternalUpdate
    
    ViewDatabaseSourcesFrame:updateView()
    self:TriggerEvent("BrownieHelper_PointsChanged")
end
